package dao;
/*
 * ConfigDAO负责把Config实例与Config表进行ORM映射
 */
import java.sql.Connection;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

import entity.Config;
import util.DBUtil;

public class ConfigDAO {
	public int getTotal() {
		int total = 0;
		try(Connection c = DBUtil.getConnection();
			Statement s = c.createStatement();){
			//统计个数，select count(*) from config
			String sql = "select count(*) from config";
			
			ResultSet rs = s.executeQuery(sql);
			while(rs.next()) {
				total = rs.getInt(1);
			}
			System.out.println("total:" + total);
		}catch (SQLException e) {
			e.printStackTrace();
		}
	return total;
	}
	
	public void add(Config config) {
		
		String sql = "insert into config values(null,?,?)";
		try(Connection c = DBUtil.getConnection();
			PreparedStatement ps = c.prepareStatement(sql);){
			
			ps.setString(1, config.getKey());
			ps.setString(2, config.getValue());
            ps.execute();
            //getGeneratedKeys获取主键
            ResultSet rs = ps.getGeneratedKeys();
            if (rs.next()) {
                int id = rs.getInt(1);
                //把config的id设置为数据库的主键，保证JAVA和数据库中数据的ID一致
                config.setId(id);
            }
		}catch(SQLException e) {
			e.printStackTrace();
		}
	}
	
	public void update(Config config) {
		
		String sql = "update config set key_=?,value=? where id = ?";
		try(Connection c = DBUtil.getConnection();
			PreparedStatement ps = c.prepareStatement(sql);){
			
			ps.setString(1, config.getKey());
			ps.setString(2, config.getValue());
			ps.setInt(3, config.getId());
			ps.execute();
			
		}catch(SQLException e) {
			e.printStackTrace();
		}
	}
	
	
}
